<template>
    <div class="page-container">
        <!-- 标题 -->
        <el-card class="card">
            <template #header>
                <div class="card-header">
                    <span class="card-title">日记详情</span>
                    <div class="card-divider"></div>
                </div>
            </template>
        </el-card>

        <!-- 文章卡片列表 -->
        <div v-for="article in articles" :key="article.id" class="card">
            <el-card>
                <template #header>
                    <div class="card-header">
                        <h2 @click="goToArticleDetail(article.id)">{{ article.title }}</h2>
                        <div class="card-meta">
                            <span>分类: {{ article.categoryName }}</span>
                            <span>发表时间: {{ article.createTime }}</span>
                            <span>状态: {{ article.state }}</span>
                        </div>
                    </div>
                </template>
                <div class="card-content">
                    <el-row :gutter="20">
                        <!-- 图片列 -->
                        <el-col :span="12">
                            <div class="grid-content">
                                <img
                                    v-if="article.coverImg"
                                    :src="article.coverImg"
                                    class="avatar"
                                    @load="handleImageLoad($event, article)"
                                    style="width: 100%; border-radius: 8px;"
                                />
                            </div>
                        </el-col>

                        <!-- 文字内容列 -->
                        <el-col :span="12">
                            <div class="grid-content" v-html="article.content"></div>
                        </el-col>
                    </el-row>
                </div>

                <div class="card-actions">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(article)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger"></el-button>
                </div>
            </el-card>
        </div>

        <!-- 分页条 -->
        <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next"
            background
            :total="total"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </div>

    <ArticleDrawer
        v-model:visible="visibleDrawer"
        :title="drawerTitle"
        :categories="categories"
        :article-model="currentArticle"
        @addArticle="handleAddArticle"
        @updateArticle="handleUpdateArticle"
        @cancel="handleDrawerCancel"
    />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { Edit, Delete } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';
import { articleListService, articleCategoryListService } from '@/api/article.js';
import {ElMessage, ElMessageBox} from 'element-plus';
import router from "@/router/index.js";
import ArticleDrawer from "@/views/article/ArticleDrawer.vue";

// 从路由中获取 categoryId 参数
const route = useRoute();
const categoryId = ref(route.query.categoryId || null);

// 文章列表数据模型
const articles = ref([]);

// 分页条数据模型
const pageNum = ref(Number(route.query.pageNum) || 1);
const pageSize = ref(Number(route.query.pageSize) || 5);
const total = ref(0); // 总条数

// 文章分类数据模型
const categories = ref([]);

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size;
    refreshArticleList();
};

// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num;
    refreshArticleList();
};

// 刷新文章列表
const refreshArticleList = async () => {
    await getArticleCategoryList();
    await getArticleList();
};

// 获取文章分类列表
const getArticleCategoryList = async () => {
    try {
        let result = await articleCategoryListService();
        categories.value = result.data;
    } catch (error) {
        ElMessage.error('获取日记分类列表失败');
    }
};

// 获取文章列表数据
const getArticleList = async () => {
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        categoryId: categoryId.value,
        state: '已发布', // 添加状态过滤条件，排除草稿状态的文章
    };
    try {
        let result = await articleListService(params);

        // 渲染视图
        total.value = result.data.total;
        articles.value = result.data.items;

        // 处理数据，给数据模型扩展一个属性 categoryName，分类名称
        for (let i = 0; i < articles.value.length; i++) {
            let article = articles.value[i];
            for (let j = 0; j < categories.value.length; j++) {
                if (article.categoryId === categories.value[j].id) {
                    article.categoryName = categories.value[j].categoryName;
                }
            }
        }
    } catch (error) {
        ElMessage.error('获取日记列表失败');
    }
};

// 显示编辑弹窗
const showDialog = (row) => {
    drawerTitle.value = '编辑日记'
    currentArticle.value = {
        ...row,
        id: row.id
    }
    visibleDrawer.value = true
}

// 处理图片加载完成事件
const handleImageLoad = (event, article) => {
    const img = event.target;
    if (img.width > img.height) {
        img.style.width = '60%';
    } else {
        img.style.width = '45%';
    }
};

// 监听路由参数变化
watch(() => route.query.categoryId, async (newVal) => {
    categoryId.value = newVal;
    await refreshArticleList();
});

onMounted(async () => {
    await refreshArticleList();
});

// 跳转到单篇文章详情页，新开一个选项卡
const goToArticleDetail = (id) => {
    const url = router.resolve({ name: 'ArticleSingle', params: { id } }).href;
    window.open(url, '_blank');
};

import { articleAddService, articleUpdateService } from '@/api/article.js'

// 新增状态管理
const visibleDrawer = ref(false)
const drawerTitle = ref('添加日记')
const currentArticle = ref({
    title: '',
    categoryId: '',
    coverImg: '',
    content: '',
    state: '',
    id: null
})

// 新增处理方法
const handleAddArticle = async (state) => {
    try {
        currentArticle.value.state = state
        const result = await articleAddService(currentArticle.value)
        ElMessage.success(result.msg || '添加成功')
        visibleDrawer.value = false
        await refreshArticleList()
    } catch (error) {
        console.error('添加失败:', error)
    }
}

const handleUpdateArticle = async (state) => {
    try {
        currentArticle.value.state = state
        const result = await articleUpdateService(currentArticle.value)
        ElMessage.success(result.msg || '修改成功')
        visibleDrawer.value = false
        await refreshArticleList()
    } catch (error) {
        console.error('更新失败:', error)
    }
}

const handleDrawerCancel = () => {
    ElMessageBox.confirm('确定要放弃修改吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        visibleDrawer.value = false
        currentArticle.value = {
            title: '',
            categoryId: '',
            coverImg: '',
            content: '',
            state: '',
            id: null
        }
    })
}

onMounted(async () => {
    await refreshArticleList()
})

</script>

<style lang="scss" scoped>
    @use "@/assets/scss/card-style";
</style>